php数组和网址URL参数的互相转换 您所在的位置:网站首页 php 转字符串 php数组和网址URL参数的互相转换

php数组和网址URL参数的互相转换

2024-04-24 01:39| 来源: 网络整理| 查看: 265

前言

接口调试和开发的过程中,相信很多小伙伴都会经常用到数组和url参数的相互转换来模拟请求。其实不用自己再通过foreach或implode之类的手动实现,php自身的函数库给我们提供了两个方法,完全够用:

一、http_build_query

将数据转换为URL参数格式,返回一个 URL 编码后的字符串。

示例: $arr = [ 'name' => 'ngxcode', 'url' => 'https://www.ngxcode.com', 'flowid' => '1001035', 'desc' => 'php share' ]; echo http_build_query($arr) . "\n"; echo http_build_query($arr, '', ';');

输出:

name=ngxcode&url=https%3A%2F%2Fwww.ngxcode.com&flowid=1001035&desc=php+share name=ngxcode;url=https%3A%2F%2Fwww.ngxcode.com;flowid=1001035;desc=php+share 二、parse_str

URL参数字符串转为数组,将字符串解析成多个变量

示例: $url_params = 'name=ngxcode&url=https%3A%2F%2Fwww.ngxcode.com&flowid=1001035&desc=php+share'; //如果设置了第二个变量 result,变量将会以数组元素的形式存入到这个数组,作为替代。 parse_str($url_params, $result); print_r($result);

输出

Array ( [name] => ngxcode [url] => https://www.ngxcode.com [flowid] => 1001035 [desc] => php share ) PHP官方文档

以下为两个函数的官方文档介绍,需要更复杂转换和解析需求的,可查看文档使用 https://www.php.net/manual/zh/function.http-build-query.php https://www.php.net/manual/zh/function.parse-str.php

原文地址:https://www.ngxcode.com/archives/519.html


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有